<?php

namespace app\shop\controller;

use app\shop\model\user\User;
use think\facade\Route as Url;

/**
 * 基类 所有控制器继承的类
 * Class AuthController
 * @package app\admin\controller
 */
class AuthController extends ShopBasic
{
    /**
     * 当前登陆管理员信息
     * @var
     */
    protected $shopInfo;

    /**
     * 当前登陆管理员ID
     * @var
     */
    protected $shopId;

    /**
     * 当前管理员权限
     * @var array
     */

    protected $skipLogController = ['index', 'common'];

    protected function initialize()
    {
        parent::initialize();
        if (!User::hasActive()) return $this->redirect(Url::buildUrl('login/index')->suffix(false)->build());
        try {
            $shopInfo = User::activeInfoOrFail();
            if (!$shopInfo) return $this->failed('请登陆', Url::buildUrl('login/index')->suffix(false)->build());
            //if (!$shopInfo['status']) return $this->failed('该账号已被关闭', Url::buildUrl('login/index')->suffix(false)->build());
            if (!$shopInfo['isshop']) return $this->failed('该账号暂未认证店铺\n无法登录', Url::buildUrl('login/index')->suffix(false)->build());

        } catch (\Exception $e) {
            return $this->failed(User::getErrorInfo($e->getMessage()), Url::buildUrl('login/index')->suffix(false)->build());
        }
        $this->shopInfo = $shopInfo;
        $this->shopId = $shopInfo['uid'];
        $this->getActiveInfo();
        $this->checkAuth();
        $this->assign('user', $this->shopInfo);
    }

    protected function checkAuth($action = null, $controller = null, $module = null, array $route = [])
    {

        if ($module === null) $module = app('http')->getName();
        if ($controller === null) $controller = $this->request->controller();
        if ($action === null) $action = $this->request->action();
        if (!count($route)) $route = $this->request->route();

        if (in_array(strtolower($controller), $this->skipLogController, true)) return true;

        $shopInfo=$this->shopInfo;
        $isshop=$shopInfo['isshop'];

        if($isshop ==-1 && strtolower($controller)!='order.storeorder'){
            return $this->failed('没有权限访问', Url::buildUrl('login/index')->suffix(false)->build());
        }

        return true;
    }


    /**
     * 获得当前用户最新信息
     * @return User
     */
    protected function getActiveInfo()
    {
        $shopId = $this->shopId;
        $shopInfo = User::getValidInfoOrFail($shopId);
        if (!$shopInfo) $this->failed('请登陆', Url::buildUrl('login/index')->suffix(false)->build());
        //if (!$shopInfo['status']) $this->failed('该账号已被关闭', Url::buildUrl('login/index')->suffix(false)->build());
        if (!$shopInfo['isshop']) return $this->failed('该账号暂未认证店铺\n无法登录', Url::buildUrl('login/index')->suffix(false)->build());

        $this->shopInfo = $shopInfo;
        User::setLoginInfo($shopInfo);
        return $shopInfo;
    }
}